package org.bmi.gwt.examples.servertoclient.server;

import org.apache.log4j.Logger;
import org.bmi.gwt.examples.servertoclient.shared.ElementProxy;
import org.bmi.gwt.examples.servertoclient.shared.PrinterProxy;
import org.bmi.gwt.mi.server.annotation.QueueHandler;
import org.bmi.gwt.mi.server.events.QueueEvent;
import org.bmi.gwt.mi.server.events.QueueEventHandler;
import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.MiTransaction;
import org.bmi.gwt.mi.shared.communication.var.ReturnVar;
import org.bmi.gwt.mi.shared.exceptions.InvalidArgumentException;

@QueueHandler(queueExpression = "org.bmi.gwt.mi.test.s2c.client")
public class ClientQueueEventHandler implements QueueEventHandler
{
	static protected Logger logger = Logger.getLogger(ClientQueueEventHandler.class);

	/*
	 * When the queue "org.bmi.gwt.mi.test.s2c.client" queue has been created
	 * this handler retrieves the source queue, creates an transactions and
	 * creates an object through a proxy; then sends several method invocations;
	 * invocations will be consumed by the client which is listening on the same
	 * queue.
	 */

	@Override
	public void onBound(QueueEvent event)
	{
		Channel source = event.getSourceQueueChannel();
		logger.info("Created queue: " + source.getExpression());

		PrinterProxy printerPrx = source.proxyToObject(PrinterProxy.class, "client_printer_id");

		MiTransaction t = source.createTransaction();
		try
		{
			/*
			 * Trying several constructors for several objects, and pushing all
			 * further method invocations to the client.
			 */

			ElementProxy p1 = t.proxyToNewObject(ElementProxy.class);
			p1.setStr("provided string");
			p1.setPrinter(printerPrx);

			/* The constructor takes as argument a return value from a function */
			ReturnVar<String> str = p1.getStr();
			ElementProxy p2 = t.proxyToNewObject(ElementProxy.class,str);
			p2.setPrinter(printerPrx);

			/* This is an example of constructor taking a proxy as argument */
			ElementProxy p3 = t.proxyToNewObject(ElementProxy.class, "String from constructor", printerPrx);

			p1.print();
			p2.print();
			p3.print();
		}
		catch (InvalidArgumentException e)
		{}

		t.commit();
	}

	@Override
	public void onCreate(QueueEvent event)
	{}

	@Override
	public void onDispose(QueueEvent event)
	{}

	@Override
	public void onUpdate(QueueEvent event)
	{}
}
